#include "BrowserViewDlg.h"
#include <QToolBar>
#include <QDesktopServices>
#include <QVBoxLayout>
BrowserViewDlg::BrowserViewDlg(const QUrl& url)
{
    progress = false;

    view = new QWebView(this);
    view->load(url);
    connect(view, SIGNAL(titleChanged(QString)), SLOT(adjustTitle()));
    connect(view, SIGNAL(loadProgress(int)), SLOT(setProgress(int)));
    connect(view, SIGNAL(loadFinished(bool)), SLOT(finishLoading(bool)));

    externalBrowser = new QPushButton(this);
    externalBrowser->setSizePolicy(QSizePolicy::Expanding, externalBrowser->sizePolicy().verticalPolicy());
    connect(externalBrowser, SIGNAL(clicked ()), SLOT(openBrowser()));

    toolBar = new QToolBar;
    toolBar->setGeometry(0,0,300,45);
    toolBar->addAction(view->pageAction(QWebPage::Back));
    toolBar->addAction(view->pageAction(QWebPage::Forward));
    toolBar->addAction(view->pageAction(QWebPage::Reload));
    toolBar->addAction(view->pageAction(QWebPage::Stop));
    toolBar->addWidget(externalBrowser);
    toolBar->setIconSize(QSize(45,45));

    QVBoxLayout *layout = new QVBoxLayout;

    label = new QLabel(tr("Loading..."));
    layout->addWidget(label);
    layout->addWidget(toolBar);
    layout->addWidget(view);

    QPushButton *close = new QPushButton("close",this);
    connect(close, SIGNAL(clicked ()), SLOT(closeClicked()));

    layout->addWidget(close);

    this->setLayout(layout);
}

void BrowserViewDlg::openBrowser(){
    QDesktopServices::openUrl(view->url().toString());
}

void BrowserViewDlg::closeClicked(){
   this->done(QDialog::Rejected);
}


void BrowserViewDlg::setTitle()
{
    if (progress)
        label->setText(view->title());
    else
        label->setText(tr("Loading..."));
}

void BrowserViewDlg::setProgress(int p)
{
    progress = false;
    setTitle();
}

void BrowserViewDlg::finishLoading(bool)
{
    progress = true;
    setTitle();
}



